package com.info.zhiduoduo.admin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Sets;
import com.info.zhiduoduo.admin.model.formbean.notice.CreateNoticeFormBean;
import com.info.zhiduoduo.admin.model.formbean.notice.NoticeListFormBean;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.NotificationConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.core.service.WxCrowdsourceMessageService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.WxPartnerMessageService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.wxmessage.WxTaxerWxMessageServiceImpl;
import com.info.zhiduoduo.repository.dto.notice.NoticeDto;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.entity.notice.Notice;
import com.info.zhiduoduo.repository.mapper.company.CompanyMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.notice.NoticeMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.wxsdk.config.WxPartnerConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class NoticeService extends BaseService {

	@Resource
	private NoticeMapper noticeMapper;
	@Resource
	private MakerMapper makerMapper;
	@Resource
	private CompanyMapper companyMapper;
	@Resource
	private PartnerMapper partnerMapper;
	@Autowired
	WxMessageService wxMessageService;
	@Autowired
	WxPartnerMessageService wxPartnerMessageService;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	WxPartnerConfig wxPartnerConfig;
	@Autowired
	CommonConfig commonConfig;
	@Autowired
	NotificationConfig notificationConfig;

	@Autowired
	WxTaxerWxMessageServiceImpl wxTaxerMessageService;

	@Autowired
	WxCrowdsourceMessageService wxCrowdsourceMessageService;

	@Resource
	private CrowdsourceAccountMapper crowdsourceAccountMapper;

	public SmartResult createNotice(BaseSimpleFormBean<CreateNoticeFormBean> formBean) {
		CreateNoticeFormBean reqdata = formBean.getReqdata();

		if (reqdata == null) return errorParamSmartResult();

		Integer noticeType = reqdata.getNoticeType();
		Integer type = reqdata.getType();
		String title = reqdata.getTitle();
		String content = reqdata.getContent();
		String url = reqdata.getUrl();
		int openingLocation = reqdata.getOpeningLocation();

		Notice notice = new Notice().setTitle(title)
				.setContent(content)
				.setNoticeType(reqdata.getNoticeType())
				.setUrl(url)
				.setType(type)
				.setManagerid(formBean.getUserid())
				.setProvinceid(reqdata.getProvinceid())
				.setCityid(reqdata.getCityid())
				.setOpeningLocation(reqdata.getOpeningLocation());

		if (notice.insert()) {
//			// 公众号中的openid
//			Set<String> zhiDuoDuoOpenids = Sets.newHashSet();
//
//			//合伙人公众号中的openid
//			Set<String> partnerOpenids = Sets.newHashSet();
//
//			//智杰祱公众号中的openid
//			Set<String> taxerOpenids = Sets.newHashSet();
//
//			//智众包公众号中的openid
//			Set<String> crowdSourceOpenids = Sets.newHashSet();
//
//			// 创客
//			List<String> zddMaker = null;
//			//智众包创客
//			List<String> crowdSourceMaker = null;
//			//自然人
//			List<String> crowdSourceNaturalPerson = null;
//			//所有企业
//			List<String> allCompanies = null;
//			//合伙人
//			List<String> partners = null;
//			//智杰祱创客
//			List<String> taxerMaker = null;
//			//智众包企业
//			List<String> crowdSourceCompany = null;
//			//普通企业
//			List<String> normalCompany = null;
//
//			//如果定向了省市，则定向推送
//			if (reqdata.getProvinceid() > 0 || reqdata.getCityid() > 0) {
//				partners = partnerMapper.getValidOpenidsByProvinceAndCity(reqdata.getProvinceid(), reqdata.getCityid());
//				crowdSourceNaturalPerson = crowdsourceAccountMapper.getAllValidOpenidsByAddress(reqdata.getProvinceid(), reqdata.getCityid());
//				if (0 != reqdata.getCityid()) {
//					String residence = reqdata.getProvinceid()+","+reqdata.getCityid();
//					//某个省市
//					zddMaker = makerMapper.getAllValidOpenidsByResidence(residence,1,MakerType.INTELL, openingLocation);
//					taxerMaker = makerMapper.getAllValidOpenidsByResidence(residence,1, MakerType.TAXER, openingLocation);
//					crowdSourceMaker = makerMapper.getAllValidOpenidsByResidence(residence,1,MakerType.CROWDSOURCE, openingLocation);
//					allCompanies = companyMapper.getAllValidOpenidsByHeadQuarters(residence,1,0);
//					normalCompany = companyMapper.getAllValidOpenidsByHeadQuarters(residence,1,1);
//					crowdSourceCompany = companyMapper.getAllValidOpenidsByHeadQuarters(residence,1,2);
//				} else {
//					String residence = reqdata.getProvinceid()+",";
//					//某个省
//					zddMaker = makerMapper.getAllValidOpenidsByResidence(residence,2, MakerType.INTELL, openingLocation);
//					taxerMaker = makerMapper.getAllValidOpenidsByResidence(residence,2,MakerType.TAXER, openingLocation);
//					crowdSourceMaker = makerMapper.getAllValidOpenidsByResidence(residence,2,MakerType.CROWDSOURCE, openingLocation);
//					allCompanies = companyMapper.getAllValidOpenidsByHeadQuarters(residence,2,0);
//					normalCompany = companyMapper.getAllValidOpenidsByHeadQuarters(residence,2,1);
//					crowdSourceCompany = companyMapper.getAllValidOpenidsByHeadQuarters(residence,2,2);
//				}
//			} else {
//				zddMaker = makerMapper.getAllValidOpenids(MakerType.INTELL,openingLocation);
//				taxerMaker = makerMapper.getAllValidOpenids(MakerType.TAXER,openingLocation);
//				allCompanies = companyMapper.getAllValidOpenids(0);
//				normalCompany = companyMapper.getAllValidOpenids(1);
//				crowdSourceCompany = companyMapper.getAllValidOpenids(2);
//				partners = partnerMapper.getAllValidOpenids();
//				crowdSourceMaker = makerMapper.getAllValidOpenids(MakerType.CROWDSOURCE,openingLocation);
//				crowdSourceNaturalPerson = crowdsourceAccountMapper.getAllValidOpenids();
//			}
//
//			if (type.equals(1)) {
//				//全部
//				zhiDuoDuoOpenids.addAll(zddMaker);
//				zhiDuoDuoOpenids.addAll(allCompanies);
//				partnerOpenids.addAll(partners);
//				taxerOpenids.addAll(taxerMaker);
//				crowdSourceOpenids.addAll(crowdSourceMaker);
//				crowdSourceOpenids.addAll(crowdSourceNaturalPerson);
//			} else if (type.equals(2)) {
//				// 创客
//				zhiDuoDuoOpenids.addAll(zddMaker);
//			} else if (type.equals(3)) {
//				//所有企业
//				zhiDuoDuoOpenids.addAll(allCompanies);
//			} else if (type.equals(4)) {
//				//合伙人
//				partnerOpenids.addAll(partners);
//			} else if (type.equals(5)) {
//				//智杰祱创客
//				taxerOpenids.addAll(taxerMaker);
//			} else if (type.equals(6)) {
//				//智众包企业
//				zhiDuoDuoOpenids.addAll(crowdSourceCompany);
//			} else if (type.equals(7)) {
//				//普通企业
//				zhiDuoDuoOpenids.addAll(normalCompany);
//			} else if (type.equals(8)) {
//				//智众包创客
//				crowdSourceOpenids.addAll(crowdSourceMaker);
//			} else if (type.equals(9)) {
//				//自然人
//				crowdSourceOpenids.addAll(crowdSourceNaturalPerson);
//			} else if (type.equals(-1)) {
//				//测试
//				List<String> testList = notificationConfig.getTestNoticeOpenids();
//				//构建数据
//				testList.forEach(openid -> {
//					Maker maker = new Maker().selectOne(Condition.create().eq("openid",openid).or().eq("taxer_openid",openid));
//					if (null != maker) {
//						//创客类型：1：  2：  3:智众包创客
//						if (2 == maker.getMakerType()) {
//							taxerOpenids.add(openid);
//						} else if (3 == maker.getMakerType()) {
//							crowdSourceOpenids.add(openid);
//						} else {
//							zhiDuoDuoOpenids.add(openid);
//						}
//					}
//				});
//			}
//			//公告详情url
//			String detailUrl = zddUrlConfig.getNoticeInfoUrl() + notice.getId();
//			//智杰祱公告详情url
//			String taxerNoticeInfoUrl = zddUrlConfig.getTaxerNoticeInfoUrl() + notice.getId();
//
//			if (!CollectionUtils.isEmpty(zhiDuoDuoOpenids)) {
//				// 平台公众号
//				zhiDuoDuoOpenids.forEach(openid -> {
//					if (noticeType == 1) {
//						//文字公告
//						wxMessageService.sendNotice(title, detailUrl, openid);
//					} else if (noticeType == 2) {
//						//链接公告
//						wxMessageService.sendSurveyNotice(title, content, url, openid);
//					}
//				});
//			}
//			if (!CollectionUtils.isEmpty(partnerOpenids)) {
//				//合伙人公共号
//				partnerOpenids.forEach(openid -> {
//					if (noticeType == 1) {
//						//文字公告
//						wxPartnerMessageService.sendNotice(notice.getTitle(), detailUrl, openid);
//					} else if (noticeType == 2) {
//						//链接公告
//						wxPartnerMessageService.sendSurveyNotice(title, content, url, openid);
//					}
//				});
//			}
//			if (!CollectionUtils.isEmpty(taxerOpenids)) {
//				//智杰祱平台公众号
//				taxerOpenids.forEach(openid ->{
//					if (1 == noticeType) {
//						//文字公告
//						wxTaxerMessageService.sendTaxerNotice(title, taxerNoticeInfoUrl, openid);
//					} else if (2 == noticeType) {
//						//链接公告
//						wxTaxerMessageService.sendTaxerSurveyNotice(title, content, url, openid);
//					}
//				});
//			}
//			if (!CollectionUtils.isEmpty(crowdSourceOpenids)) {
//				//智众包平台公众号
//				crowdSourceOpenids.forEach(openid ->{
//					if (1 == noticeType) {
//						//文字公告
//						wxCrowdsourceMessageService.sendNotice(title, detailUrl, openid);
//					} else if (2 == noticeType) {
//						//链接公告
//						wxCrowdsourceMessageService.sendSurveyNotice(title, content, url, openid);
//					}
//				});
//			}
			return smartResult(notice.getId());
		}
		return optFailSmartResult();
	}

	public SmartResult getNoticeList(BaseSimpleFormBean<NoticeListFormBean> formBean) {
		NoticeListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String title = reqdata.getTitle();
		int type = reqdata.getType();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		noticeMapper.getList(title, type, startDate, endDate);
		return smartResultPage(page);
	}

	public SmartResult getDetail(BaseSimpleFormBean<Integer> formBean) {
		Integer reqdata = formBean.getReqdata();
		NoticeDto detail = noticeMapper.getDetail(reqdata);
		return smartResult(detail);
	}

	public SmartResult delNotice(BaseSimpleFormBean<Integer> formBean) {
		Integer noticeid = formBean.getReqdata();
		boolean b = new Notice().deleteById(noticeid);
		return smartResult();
	}

	public SmartResult specifyCreate(CreateNoticeFormBean reqdata,int userId) {
		Integer noticeType = reqdata.getNoticeType();
		Integer type = reqdata.getType();
		String title = reqdata.getTitle();
		String content = reqdata.getContent();
		String url = reqdata.getUrl();
		int specifyId = reqdata.getSpecifyId();

		Notice notice = new Notice().setTitle(title)
				.setContent(content)
				.setNoticeType(reqdata.getNoticeType())
				.setUrl(url)
				.setType(type)
				.setManagerid(userId)
				.setProvinceid(reqdata.getProvinceid())
				.setCityid(reqdata.getCityid())
				.setOpeningLocation(reqdata.getOpeningLocation())
				.setSpecifyId(specifyId);
		if (notice.insert()) {
			//公告详情url
			String detailUrl = zddUrlConfig.getNoticeInfoUrl() + notice.getId();
			//智杰祱公告详情url
			String taxerNoticeInfoUrl = zddUrlConfig.getTaxerNoticeInfoUrl() + notice.getId();
			// 公众号中的openid
			Set<String> zhiDuoDuoOpenids = Sets.newHashSet();
			//合伙人公众号中的openid
			Set<String> partnerOpenids = Sets.newHashSet();
			//智杰祱公众号中的openid
			Set<String> taxerOpenids = Sets.newHashSet();
			//智众包公众号中的openid
			Set<String> crowdSourceOpenids = Sets.newHashSet();

			if (type == 10) {
				Maker maker = makerMapper.selectById(specifyId);
				if (null == maker){
					return emptyDataSmartResult();
				}
				if (maker.getMakerType() == 1){
					zhiDuoDuoOpenids.add(maker.getOpenid());
				} else if (maker.getMakerType() == 2){
					taxerOpenids.add(maker.getTaxerOpenid());
				} else if (maker.getMakerType() == 3){
					crowdSourceOpenids.add(maker.getOpenid());
				}
			} else if (type == 11) {
				zhiDuoDuoOpenids.add(companyMapper.getValidOpenId(specifyId));
			} else if (type == 12) {
				partnerOpenids.add(partnerMapper.getValidOpenId(specifyId));
			} else if (type == 13) {
				crowdSourceOpenids.add(crowdsourceAccountMapper.getValidOpenId(specifyId));
			}

			if (!CollectionUtils.isEmpty(zhiDuoDuoOpenids)) {
				// 平台公众号
				zhiDuoDuoOpenids.forEach(openid -> {
					if (noticeType == 1) {
						//文字公告
						wxMessageService.sendNotice(title, detailUrl, openid);
					} else if (noticeType == 2) {
						//链接公告
						wxMessageService.sendSurveyNotice(title, content, url, openid);
					}
				});
			}

			if (!CollectionUtils.isEmpty(partnerOpenids)) {
				//合伙人公共号
				partnerOpenids.forEach(openid -> {
					if (noticeType == 1) {
						//文字公告
						wxPartnerMessageService.sendNotice(notice.getTitle(), detailUrl, openid);
					} else if (noticeType == 2) {
						//链接公告
						wxPartnerMessageService.sendSurveyNotice(title, content, url, openid);
					}
				});
			}

			if (!CollectionUtils.isEmpty(taxerOpenids)) {
				//智杰祱平台公众号
				taxerOpenids.forEach(openid ->{
					if (1 == noticeType) {
						//文字公告
						wxTaxerMessageService.sendTaxerNotice(title, taxerNoticeInfoUrl, openid);
					} else if (2 == noticeType) {
						//链接公告
						wxTaxerMessageService.sendTaxerSurveyNotice(title, content, url, openid);
					}
				});
			}

			if (!CollectionUtils.isEmpty(crowdSourceOpenids)) {
				//智众包平台公众号
				crowdSourceOpenids.forEach(openid ->{
					if (1 == noticeType) {
						//文字公告
						wxCrowdsourceMessageService.sendNotice(title, detailUrl, openid);
					} else if (2 == noticeType) {
						//链接公告
						wxCrowdsourceMessageService.sendSurveyNotice(title, content, url, openid);
					}
				});
			}

			return smartResult(notice.getId());
		}
		return optFailSmartResult();
	}
}
